import Vue from 'vue'
// -------------------------------------------------------
import login from '@/views/login/login.vue'
import layout from '@/views/layout/layout.vue'
import chart from '@/views/layout/chart/chart.vue'
import userList from '@/views/layout/userList/userList.vue'
import question from '@/views/layout/question/question.vue'
import business from '@/views/layout/business/business.vue'
import subject from '@/views/layout/subject/subject.vue'
// -------------------------------------------------------
// 进度条
import  NProgress from 'nprogress'
import "nprogress/nprogress.css"
import VueRouter from 'vue-router'
import { Message } from 'element-ui'
import {localRemove} from '@/utils/token.js'
import store from '@/store/index.js'

Vue.use(VueRouter)
const router = new VueRouter({
   routes:[{
    path:'/',
    component:login,
    meta:{
       title:"登录",
       roleArr:["超级管理员","管理员","老师","学生"]
      }
   },
   {
      path:'/layout',
      redirect:'/layout/userList',
      component:layout,
      children:[
         {
          path:'chart',
          component:chart ,
          meta:{
             title:"数据概览",
             roleArr:["超级管理员","管理员","老师"]
            } 
         },
         {
            path:'userList',
            component:userList,
            meta:{
               title:"用户列表",
               roleArr:["超级管理员","管理员"]
            }  
           },
           {
            path:'question',
            component:question,
            meta:{
               title:"题库列表",
               roleArr:["超级管理员","管理员","老师"]
            }    
           },
           {
            path:'business',
            component:business,
            meta:{
               title:"企业列表",
               roleArr:["超级管理员","管理员","老师"]
            }    
           },
           {
            path:'subject',
            component:subject,
            meta:{
               title:"学科列表",
               roleArr:["超级管理员","管理员","老师","学生"]
            }    
           },
      ]
     }
] 
})
// 点击重复路由报错的解决方法
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
   return originalPush.call(this, location).catch(err =>err)
}

// 导航守卫-------------------------------------------------
// 1. 路由进入前处理
router.beforeEach((to, from, next) => {
   NProgress.start()
   window.console.log(to,from);
   if(to.meta.roleArr.includes(store.state.role)){
      next()
   }else{
      // 提示用户
      Message.warning("您无权访问该页面")
      // 删除token
      localRemove()
      // 跳转至登录页
      next('/')
   }
   
   // to and from are both route objects. must call `next`.
})
// 2.路由进入后处理
router.afterEach((to, from) => {
   document.title=to.meta.title
   window.console.log(to,from);
   // to and from are both route objects.
   NProgress.done()
})
// ---------------------------------------------------------

export default router